<template>
  <div>
    <h1 id="last">现金流入</h1>
    <div class="controls">
      <input id="searchQuery" v-model="searchQuery" type="text" placeholder="搜索收入项目" @input="applyFilters" />
      开始日期：<input v-model="startDate" type="date" @change="applyFilters" />
      截止日期：<input v-model="endDate" type="date" @change="applyFilters" />
      <button class="repeat" @click="resetFilters">重置</button>
      <button class="add" @click="showPopup">新增</button>
      <button class="out" @click="exportExcel">导出excel文件</button>
    </div>
    <table class="tab" id="cashTable">
      <thead>
        <tr>
          <th>收入项目</th>
          <th>月初现金</th>
          <th>收入金额</th>
          <th>月末现金</th>
          <th>时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in paginatedData" :key="index">
          <td>{{ item.income_item }}</td>
          <td>{{ formatAmount(item.openingBalance) }}</td>
          <td>{{ formatAmount(item.amount) }}</td>
          <td>{{ formatAmount(item.final_cash) }}</td>
          <td>{{ item.date }}</td>
          <td>
            <button class="bianji" @click="editItem(index)">编辑</button>
            <button class="shanchu" @click="deleteItem(index)">删除</button>
          </td>
        </tr>
        <tr>
          <td colspan="2">总收入</td>
          <td>{{ formatAmount(totalAmount) }}</td>
          <td>{{ formatAmount(totalEndingBalance) }}</td>
          <td colspan="2"></td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>

    <!-- 新增弹窗 -->
    <div v-if="showAddPopup" class="popup">
      <div class="popup-content">
        <span class="close" @click="showAddPopup = false">&times;</span>
        <h2>新增收入</h2>
        <label for="item">收入项目：</label>
        <div class="select-container">
          <select v-model="newItem.income_item" id="item" class="input">
            <option v-for="option in itemOptions" :key="option" :value="option">
              {{ option }}
            </option>
          </select>
        </div>
        <label for="openingBalance">月初现金：</label>
        <input v-model.number="newItem.openingBalance" type="number" id="openingBalance" placeholder="请输入:" />
        <label for="amount">收入金额：</label>
        <input v-model.number="newItem.amount" type="number" id="amount" placeholder="请输入:" />
        <label for="date">时间：</label>
        <input v-model="newItem.date" type="date" id="date" />
        <button @click="addItem">提交保存</button>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <div v-if="showEditPopup" class="popup">
      <div class="popup-content">
        <span class="close" @click="showEditPopup = false">&times;</span>
        <h2>编辑收入</h2>
        <label for="editItem">收入项目：</label>
        <input v-model="editItemData.income_item" type="text" id="editItem" placeholder="请输入:" />
        <label for="editOpeningBalance">月初现金：</label>
        <input v-model.number="editItemData.openingBalance" type="number" id="editOpeningBalance" placeholder="请输入:" />
        <label for="editAmount">收入金额：</label>
        <input v-model.number="editItemData.amount" type="number" id="editAmount" placeholder="请输入:" />
        <label for="editDate">时间：</label>
        <input v-model="editItemData.date" type="date" id="editDate" />
        <button @click="updateItem">更新</button>
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  data() {
    return {
      cashData: [],
      showAddPopup: false,
      showEditPopup: false,
      newItem: {
        income_item: '',
        openingBalance: 0,
        amount: 0,
        date: ''
      },
      editIndex: null,
      editItemData: {
        income_item: '',
        openingBalance: 0,
        amount: 0,
        date: ''
      },
      searchQuery: '',
      startDate: '',
      endDate: '',
      currentPage: 1,
      itemsPerPage: 8,
      itemOptions: [
        '银行贷款',
        '投资收入',
        '租金收入',
        '礼金',
        '其他收入',
        '自筹资金',
        '风险投资'
      ],
    };
  },
  created() {
    this.userId = localStorage.getItem('userId');
    if (this.userId) {
      this.fetchData(); // 获取数据
    } else {
      alert('请先登录');
      this.$router.push('/login');
    }
  },
  computed: {
    filteredData() {
      return this.cashData.filter(item => {
        if (!item) return false; // 处理 undefined 或 null 项目
        const matchesSearch = item.income_item.includes(this.searchQuery);
        const matchesStartDate = !this.startDate || new Date(item.date) >= new Date(this.startDate);
        const matchesEndDate = !this.endDate || new Date(item.date) <= new Date(this.endDate);
        return matchesSearch && matchesStartDate && matchesEndDate;
      });
    },
    totalPages() {
      return Math.ceil(this.filteredData.length / this.itemsPerPage);
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredData.slice(start, end);
    },
    totalAmount() {
      return this.filteredData.reduce((sum, item) => sum + parseFloat(item.amount || 0), 0);
    },
    totalEndingBalance() {
      return this.filteredData.reduce((sum, item) => sum + parseFloat(item.final_cash || 0), 0); // 确保字段名正确
    },
  },
  methods: {
    fetchData() {
      fetch(`http://82.156.19.25:5000/get_income_data?user_id=${this.userId}`)
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            this.cashData = data.income.map(item => ({
              ...item,
              openingBalance: parseFloat(item.initial_cash || 0),
              amount: parseFloat(item.amount || 0),
              final_cash: parseFloat(item.final_cash || 0),
            }));

            // 根据id进行降序排序
            this.cashData.sort((a, b) => b.id - a.id);

          } else {
            alert('获取数据失败: ' + data.message);
          }
        })
        .catch(error => {
          console.error('获取数据时发生错误:', error);
          alert('网络请求失败，请稍后再试。');
        });
    },
    addItem() {
  if (this.newItem.income_item && this.newItem.openingBalance && this.newItem.amount && this.newItem.date) {
    this.newItem.final_cash = parseFloat(this.newItem.openingBalance) + parseFloat(this.newItem.amount);

    fetch('http://82.156.19.25:5000/add_income_data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        user_id: this.userId,
        income_item: this.newItem.income_item,
        initial_cash: this.newItem.openingBalance,
        amount: this.newItem.amount,
        final_cash: this.newItem.final_cash,
        date: this.newItem.date
      })
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        // 新增数据成功后，刷新页面
        window.location.reload();
      } else {
        alert('添加数据失败');
      }
    })
    .catch(error => {
      console.error('Error:', error);
      alert('网络请求失败，请稍后再试。');
    });
  } else {
    alert('请填写所有字段');
  }
},
    editItem(index) {
      this.editIndex = index;
      const item = this.paginatedData[index];
      this.editItemData = { ...item };
      this.showEditPopup = true;
    },
   updateItem() {
  if (this.editItemData.income_item && this.editItemData.openingBalance && this.editItemData.amount && this.editItemData.date) {
    this.editItemData.final_cash = parseFloat(this.editItemData.openingBalance) + parseFloat(this.editItemData.amount);

    fetch('http://82.156.19.25:5000/update_income_data', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        id: this.editItemData.id,
        user_id: this.userId,
        income_item: this.editItemData.income_item,
        initial_cash: this.editItemData.openingBalance,
        amount: this.editItemData.amount,
        final_cash: this.editItemData.final_cash,
        date: this.editItemData.date
      })
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          // 更新成功，重新获取数据
          this.fetchData();
          this.showEditPopup = false;
          this.editIndex = null;
        } else {
          alert('更新数据失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        alert('网络请求失败，请稍后再试。');
      });
  } else {
    alert('请填写所有字段');
  }
},
    deleteItem(index) {
  const item = this.paginatedData[index];
  const userId = this.userId; // 确保 this.userId 已经设置
  console.log('UserId:', userId); // 调试 userId
  if (confirm(`确定要删除项目"${item.income_item}"吗？`)) {
    fetch(`http://82.156.19.25:5000/delete_income_data`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ user_id: userId, id: item.id })
    })
    .then(response => {
      if (response.headers.get('content-type')?.includes('application/json')) {
        return response.json();
      } else {
        throw new Error('Invalid JSON response');
      }
    })
    .then(data => {
      if (data.success) {
        this.fetchData();
      } else {
        alert('删除数据失败: ' + data.message);
      }
    })
    .catch(error => {
      console.error('Error:', error);
      alert('网络请求失败，请稍后再试。');
    });
  }
},
    applyFilters() {
      this.currentPage = 1; // 重置为第一页
    },
    resetFilters() {
      this.searchQuery = '';
      this.startDate = '';
      this.endDate = '';
      this.currentPage = 1;
    },
    resetNewItem() {
      this.newItem = {
        income_item: '',
        openingBalance: 0,
        amount: 0,
        date: ''
      };
    },
    formatAmount(amount) {
      return amount.toFixed(2);
    },
    exportExcel() {
  // 获取表格数据
  const tableData = this.filteredData.map(item => [
    item.income_item,                  // 收入项目
    this.formatAmount(item.openingBalance), // 月初现金
    this.formatAmount(item.amount),         // 收入金额
    this.formatAmount(item.final_cash),     // 月末现金
    item.date                            // 时间
  ]);

  // 添加表头
  tableData.unshift(['收入项目', '月初现金', '收入金额', '月末现金', '时间']);

  // 计算总收入和总月末现金
  const totalAmount = this.filteredData.reduce((sum, item) => sum + parseFloat(item.amount), 0);
  const totalEndingBalance = this.filteredData.reduce((sum, item) => sum + parseFloat(item.final_cash), 0);

  // 添加总收入行
  tableData.push(['总收入', '', this.formatAmount(totalAmount), this.formatAmount(totalEndingBalance), '']);

  // 创建工作表和工作簿
  const ws = XLSX.utils.aoa_to_sheet(tableData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '现金流入');

  // 导出 Excel 文件
  XLSX.writeFile(wb, '现金流入.xlsx');
},
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },
    showPopup() {
      this.resetNewItem(); // 重置 newItem 数据
      this.showAddPopup = true; // 显示弹窗
    }
  }
};
</script>
<style scoped>
.searchQuery{
  margin-left: 125px;
}
body {
  font-family: Arial, sans-serif;
  background-color: #062745;
  align-items: center;
  flex-direction: column;
  min-height: 100vh;
  margin: 0;
}

body {
    font-family: Arial, sans-serif;
    background-color: #062745;
    align-items: center;
    flex-direction: column;
    min-height: 100vh;
    margin: 0;
  }
  
  .controls {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .controls input[type='text']{
    margin-left: 125px;
    margin-right: 10px;
    padding: 5px;
    border-radius: 4px;
    border: 1px solid #ddd;
  }
  .controls input[type='date'],
  .controls input[type='month'] {
    margin-left: 10px;
    margin-right: 10px;
    padding: 5px;
    border-radius: 4px;
    border: 1px solid #ddd;
  }
  
  table {
    border-collapse: collapse;
    width: 80%;
    margin: 20px 0;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    background-color: #fff;
  }
  
  th,
  td {
    border: 1px solid #ddd;
    padding: 12px 15px;
    text-align: center;
  }
  
  th {
    background-color: #4caf50;
    color: white;
  }
  
  tr:nth-child(even) {
    background-color: #f2f2f2;
  }
  
  tr:hover {
    background-color: #f1f1f1;
  }
  
  h1 {
    margin-left: 15px;
  }
  .repeat,
  .add,
  .out,
  .bianji,
  .shanchu {
    margin-bottom: 5px;
    margin-top: 10px;
    margin-left: 10px;
    border-radius: 8px;
    border-style: none;
    padding: 5px 20px;
    font-size: 15px;
    color: white;
    transition: background-color 0.3s;
  }
  .repeat {
    background-color: rgb(134, 173, 16);
  }
  .add {
    background-color: rgb(27, 128, 7);
  }
  .out {
    background-color: #f07c3e;
  }
  .bianji {
    background-color: rgb(201, 43, 31);
  }
  .shanchu {
    background-color: rgb(9, 4, 48);
  }
  .out:hover,
  .add:hover,
  .bianji:hover,
  .shanchu:hover {
    background-color: rgb(103, 17, 240);
  }
  
  .tab {
    margin-left: 125px;
  }
  
  button {
    cursor: pointer;
  }
  
  .popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .popup-content {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    width: 300px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    position: relative;
  }
  
  .close {
    position: absolute;
    right: 20px;
    top: 20px;
    cursor: pointer;
    font-size: 18px;
    color: #333;
  }
  
  .popup-content input[type='text'],
  .popup-content input[type='number'],
  .popup-content input[type='date'] {
    width: 100%;
    padding: 8px;
    margin-bottom: 15px;
    border-radius: 4px;
    border: 1px solid #ddd;
    font-size: 14px;
  }
  
  input[type='text']:focus,
  input[type='number']:focus,
  input[type='date']:focus,
  select:focus {
    border-color: #4caf50;
}
  
  button {
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 5px;
    padding: 12px 24px;
    cursor: pointer;
    margin-top: 10px;
    transition: background-color 0.3s;
  }
  
  button:hover {
    background-color: #45a049;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
  }
  
  .pagination button {
    margin: 0 5px;
    padding: 8px 16px;
    border-radius: 4px;
    background-color: #f2f2f2;
    color: #333;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s;
  }
  
  .pagination button:hover {
    background-color: #ddd;
  }
  .select-container select {
  width: 105%;
  padding: 12px 24px; /* 增加内边距 */
  font-size: 15px; /* 增大字体 */
  height: 45px; /* 增大高度 */
  border-radius: 4px; /* 圆角 */
  background-repeat: no-repeat;
  background-position: right 10px center;
  background-size: 16px;
}
table th:nth-child(4),
table td:nth-child(4) {
  width: 150px;
}
.popup-content label,
.popup-content input {
  display: block;
  margin-bottom: 10px;
}

.popup-content input[type="number"] {
  width: 100%;
}

.popup-content .input {
  width: 100%;
}

.tab th,
.tab td {
  text-align: center;
}

.controls {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 10px;
}

.popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  max-width: 500px;
  width: 100%;
}

.close {
  float: right;
  font-size: 20px;
  cursor: pointer;
}

button {
  margin-top: 10px;
}

</style>
